import {ref, computed, watch} from 'vue'
import {defineStore} from 'pinia'

export interface Sku {
    skuId: string,
    name: string,
    price: number,
    oldPrice: number,
    inventory: number,
    specsText: string,
    picUrl: string,
    count: number,
    selected: boolean,
}

const useCartStore = defineStore('cart', () => {
    const list = ref<Sku[]>([])
    const selectList  = ref<Sku[]>([])
    const getCartList = () => {
        const cartList = localStorage.getItem('cart')
        if (cartList) {
            list.value = JSON.parse(cartList)
        }
        return list.value
    }
    const addCart = (sku: Sku) => {
        const index = list.value.findIndex(item => item.skuId === sku.skuId)
        if (index === -1) {
            list.value.push(sku)
        } else {
            list.value[index].count += sku.count
        }
        localStorage.setItem('cart', JSON.stringify(list.value))
    }
    const delCart = (skuId: string) => {
        list.value = list.value.filter(item => item.skuId !== skuId)
        localStorage.setItem('cart', JSON.stringify(list.value))
    }
    const changeCartCount = (skuId: string, count: number) => {
        const index = list.value.findIndex(item => item.skuId === skuId)
        if (index !== -1) {
            list.value[index].count = count
        }
        localStorage.setItem('cart', JSON.stringify(list.value))
     }
     const changeCartSelected = (arr:Sku[]) => {
        list.value = arr
        localStorage.setItem('cart', JSON.stringify(list.value))
     }
     watch(()=>{
         return list.value.map(item => item.selected)
     }, () => {
         selectList.value = list.value.filter(item => item.selected)
     },{deep: true})
    return {
        list,
        selectList,
        addCart,
        getCartList,
        delCart,
        changeCartCount,
        changeCartSelected
    }
})
export default useCartStore